<template>
  <div class="role-management-container">
    <!-- 查询区域 -->
    <div class="search-area">
      <el-input
        v-model="searchQuery.username"
        placeholder="请输入用户名"
        clearable
        style="width: 220px"
        @keyup.enter.native="handleSearch"
      />
      <el-button
        type="primary"
        style="margin-left: 10px"
        @click="handleSearch"
      >
        查询
      </el-button>
      <!-- <el-button
        type="primary"
        style="margin-left: 10px"
        @click="showAddDialog"
      >
        添加角色
      </el-button> -->
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="currentPageData"
      border
      style="width: 100%; margin-top: 20px"
      :header-cell-style="{
        background: '#f5f7fa',
        color: '#606266',
        fontWeight: 'bold'
      }"
    >
      <el-table-column
        prop="id"
        label="ID"
        width="80"
        align="center"
      />
      <el-table-column
        prop="username"
        label="用户名"
        align="center"
      />
      <el-table-column
        prop="applyRole"
        label="申请角色类型"
        align="center"
      >
        <template slot-scope="scope">
          <el-tag :type="scope.row.applyRole == 1 ? 'primary' : 'success'">
            {{ formatRoleType(scope.row.applyRole) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="plateId"
        label="申请板块"
        align="center"
        width="180"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.applyRole === 2">
            {{ scope.row.plateId }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>

      <el-table-column
        prop="status"
        label="状态"
        align="center"
        width="140"
      >
        <template slot-scope="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="applyTime"
        label="申请时间"
        align="center"
        width="200"
      />
      <el-table-column
        prop="applyReason"
        label="申请原因"
        align="center"
        width="350"
      />
      <el-table-column
        prop="approveTime"
        label="通过时间"
        align="center"
        width="200"
      />
      <el-table-column
        label="操作"
        align="center"
        width="220"
      >
        <template slot-scope="scope">
          <!-- 关键修改：使用数字状态判断但保留中文显示 -->
          <el-button
            v-if="scope.row.status === '待审核' && scope.row._status === 0"
            size="mini"
            type="success"
            @click="handleApprove(scope.row)"
          >
            通过
          </el-button>
          <el-button
            v-if="scope.row.status === '待审核' && scope.row._status === 0"
            size="mini"
            type="warning"
            @click="handleReject(scope.row)"
          >
            拒绝
          </el-button>
          <el-button
            size="mini"
            type="info"
            @click="showDetail(scope.row)"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <span>共 {{ filteredRoleList.length }} 条</span>
      <el-select
        v-model="pagination.pageSize"
        size="mini"
        style="width: 100px; margin: 0 15px"
        @change="handleSizeChange"
      >
        <el-option
          v-for="item in [10,20,30]"
          :key="item"
          :label="`${item}条/页`"
          :value="item"
        />
      </el-select>
      <el-pagination
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        layout="prev, pager, next, jumper"
        :total="filteredRoleList.length"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加角色对话框
    <el-dialog
      title="添加角色申请"
      :visible.sync="addDialogVisible"
      width="40%"
      :modal="false"
    >
      <el-form
        :model="newRoleForm"
        label-width="120px"
      > -->
    <!-- 显示当前用户（不编辑）
        <el-form-item label="申请人">
          <el-input
            :value="currentUser.nickname"
            disabled
            placeholder="系统自动获取当前用户"
          />
        </el-form-item>

        <el-form-item
          label="申请角色类型"
          prop="roleType"
          required
        >
          <el-select
            v-model="newRoleForm.roleType"
            placeholder="请选择"
            @change="handleRoleTypeChange"
          >
            <el-option
              label="产品体验官"
              :value="1"
            />
            <el-option
              label="版主"
              :value="2"
            />
          </el-select>
        </el-form-item>

        动态显示板块选择 -->
    <!-- <el-form-item
          v-if="newRoleForm.roleType === 2"
          label="申请板块"
          prop="plateId"
          :required="newRoleForm.roleType === 2"
        >
          <el-select
            v-model="newRoleForm.plateId"
            placeholder="请选择要管理的板块"
            clearable
          >
            <el-option
              v-for="plate in plateList"
              :key="plate.plateId"
              :label="plate.plateName"
              :value="plate.plateId"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="申请理由"
          prop="reason"
          required
        >
          <el-input
            v-model="newRoleForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请详细说明申请理由（至少20字）"
            show-word-limit
            :minlength="20"
          />
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="addDialogVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          :loading="submitting"
          @click="submitApplication"
        >
          提交申请
        </el-button>
      </div>
    </el-dialog> -->

    <!-- 详情对话框 -->
    <el-dialog
      title="申请详情"
      :visible.sync="detailDialogVisible"
      width="50%"
      :modal="false"
    >
      <el-descriptions
        :column="1"
        border
      >
        <el-descriptions-item label="ID">
          {{ currentDetail.id }}
        </el-descriptions-item>
        <el-descriptions-item label="用户名">
          {{ currentDetail.username }}
        </el-descriptions-item>
        <el-descriptions-item label="申请角色类型">
          {{ formatRoleType(currentDetail.applyRole) }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTagType(currentDetail.status)">
            {{ currentDetail.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="申请时间">
          {{ currentDetail.applyTime }}
        </el-descriptions-item>
        <el-descriptions-item label="申请原因">
          {{ currentDetail.applyReason }}
        </el-descriptions-item>
        <el-descriptions-item label="通过时间">
          {{ currentDetail.approveTime || '无' }}
        </el-descriptions-item>
      </el-descriptions>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="detailDialogVisible = false"
        >关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import $ from 'jquery'

export default {
  data () {
    return {
      searchQuery: {
        username: ''
      },
      roleList: [], // 初始为空数组，将从后端获取数据
      activeFilter: null,
      pagination: {
        currentPage: 1,
        pageSize: 10
      },
      addDialogVisible: false,
      newRoleForm: {
        username: '',
        applyRole: '',
        applyReason: ''
      },
      detailDialogVisible: false,
      currentDetail: {},
      currentUser: {
        accountId: null, // 初始值设为null
        nickname: '' // 初始空字符串
      },
      submitting: false // 控制提交按钮的加载状态
    }
  },
  computed: {
    filteredRoleList () {
      if (!this.activeFilter) return this.roleList
      return this.roleList.filter(role =>
        role.username.toLowerCase().includes(this.activeFilter.toLowerCase())
      )
    },
    currentPageData () {
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize
      const end = start + this.pagination.pageSize
      return this.filteredRoleList.slice(start, end)
    }
  },
  created () {
    this.fetchRoleList()
  },
  methods: {
    fetchRoleList () {
      $.ajax({
        url: 'http://localhost:3000/api/getAllRoleApplications',
        method: 'GET',
        dataType: 'json',
        success: (response) => {
          if (response.code === 200) {
            console.log(response.data)
            this.roleList = response.data.map((item) => {
              const formatTime = (timeArr) => {
                if (!timeArr || timeArr.length !== 6) return ''
                return `${timeArr[0]}-${String(timeArr[1]).padStart(2, '0')}-${String(timeArr[2]).padStart(2, '0')} ` +
                  `${String(timeArr[3]).padStart(2, '0')}:${String(timeArr[4]).padStart(2, '0')}:${String(timeArr[5]).padStart(2, '0')}`
              }
              return {
                id: item.roleApplication.roleApplicationId,
                username: item.user.nickname,
                applyRole: item.roleApplication.roleType,
                plateId: item.roleApplication.plateId || '未指定', // 直接从roleApplication取plateId
                status: this.formatStatus(item.roleApplication.status),
                // 新增此行（其他字段保持不变）
                _status: item.roleApplication.status, // 原始数字状态
                // 必须包含的审批参数
                accountId: item.user.accountId, // 从user对象获取
                roleType: item.roleApplication.roleType, // 从roleApplication获取
                applyTime: formatTime(item.roleApplication.createTime),
                applyReason: item.roleApplication.reason,
                approveTime: formatTime(item.roleApplication.passTime)
              }
            })
          } else {
            this.$message.error(response.message || '获取角色列表失败')
          }
        },
        error: (xhr) => {
          this.$message.error(`获取失败: ${xhr.responseJSON?.message || xhr.statusText}`)
        }
      })
    },

    // 添加状态格式化方法
    formatStatus (status) {
      switch (status) {
      case 0: return '待审核'
      case 1: return '已通过'
      case 2: return '已拒绝'
      default: return '未知状态'
      }
    },

    // 格式化角色类型显示
    formatRoleType (type) {
      // 处理数字1/2或字符串"1"/"2"的情况
      const roleType = String(type).trim() // 转为字符串并去除空格
      const roleMap = {
        1: '产品体验官',
        2: '版主'
      }
      return roleMap[roleType] || `未知类型(${type})`
    },

    getStatusTagType (status) {
      switch (status) {
      case '已通过': return 'success'
      case '已拒绝': return 'danger'
      default: return 'warning'
      }
    },

    handleSearch () {
      this.activeFilter = this.searchQuery.username
      this.pagination.currentPage = 1
    },

    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
    },

    handleCurrentChange (val) {
      this.pagination.currentPage = val
    },

    showAddDialog () {
      this.newRoleForm = {
        username: '',
        applyRole: '',
        applyReason: ''
      }
      this.addDialogVisible = true
    },

    // 处理角色类型变化
    handleRoleTypeChange (val) {
      if (val !== 2) {
        this.newRoleForm.plateId = null
      }
    },

    //   // 提交申请的处理方法
    //   submitApplication () {
    //     // 表单验证
    //     if (!this.newRoleForm.roleType) {
    //       this.$message.warning('请选择角色类型')
    //       return
    //     }

    //     if (this.newRoleForm.roleType === 2 && !this.newRoleForm.plateId) {
    //       this.$message.warning('请选择要管理的板块')
    //       return
    //     }

    //     if (!this.newRoleForm.reason || this.newRoleForm.reason.length < 5) {
    //       this.$message.warning('请填写至少50字的申请理由')
    //       return
    //     }

    //     this.submitting = true

    //     const postData = {
    //       accountId: this.currentUser.accountId,
    //       roleType: this.newRoleForm.roleType,
    //       reason: this.newRoleForm.reason,
    //       plateId: this.newRoleForm.roleType === 2 ? this.newRoleForm.plateId : null
    //     }

    //     $.ajax({
    //       url: 'http://localhost:3000/api/insertRoleApplication',
    //       method: 'POST',
    //       contentType: 'application/json',
    //       data: JSON.stringify(postData),
    //       success: (res) => {
    //         this.submitting = false
    //         if (res.code === 200) {
    //           this.$message.success('申请提交成功')
    //           this.addDialogVisible = false
    //           this.fetchRoleList()
    //         } else {
    //           this.$message.error(res.message || '提交失败')
    //         }
    //       },
    //       error: (xhr) => {
    //         this.submitting = false
    //         this.$message.error(`提交失败: ${xhr.responseJSON?.message || xhr.statusText}`)
    //       }
    //     })
    //   }
    // },

    handleApprove (row) {
      // 参数验证
      if (!row.accountId || !row.roleType) {
        this.$message.error(`参数缺失: accountId=${row.accountId}, roleType=${row.roleType}`)
        return
      }

      this.$confirm('确定通过该申请吗?', '提示').then(() => {
        const formData = new FormData()
        formData.append('accountId', row.accountId)
        formData.append('status', 1)
        formData.append('accountType', row.roleType)

        // 使用 jQuery.ajax 替代 $axios
        $.ajax({
          url: 'http://localhost:3000/api/auditRoleApplication',
          type: 'POST',
          data: formData,
          processData: false, // 必须设置
          contentType: false, // 必须设置
          success: (response) => {
            if (response.code === 200) {
              this.$message.success('已通过申请')
              this.fetchRoleList()
            } else {
              this.$message.error(response.message || '操作失败')
            }
          },
          error: (xhr) => {
            console.error('审批请求失败:', xhr.statusText)
            this.$message.error('请求失败，请检查网络')
          }
        })
      }).catch(() => {
        this.$message.info('已取消操作')
      })
    },

    handleReject (row) {
      // 参数验证
      if (!row.accountId) {
        this.$message.error(`参数缺失: accountId=${row.accountId}`)
        return
      }

      this.$prompt('请输入拒绝理由', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.{1,200}$/,
        inputErrorMessage: '拒绝理由长度应在1-200个字符之间',
        type: 'warning'
      }).then(({ value }) => {
        if (!value || value.trim() === '') {
          this.$message.error('拒绝理由不能为空')
          return
        }

        const formData = new FormData()
        formData.append('accountId', row.accountId)
        formData.append('status', 2) // 2表示拒绝
        formData.append('rejectReason', value.trim())

        // 关键修改：添加默认的accountType（即使拒绝操作不需要）
        formData.append('accountType', 0) // 使用默认值0

        $.ajax({
          url: 'http://localhost:3000/api/auditRoleApplication',
          type: 'POST',
          data: formData,
          processData: false,
          contentType: false,
          success: (response) => {
            if (response.code === 200) {
              this.$message.success('已拒绝申请')
              this.fetchRoleList()
            } else {
              // 处理507错误（服务器繁忙）
              if (response.code === 507) {
                this.$message.warning('服务器繁忙，请10秒后重试')
              } else {
                this.$message.error(response.message || '操作失败')
              }
            }
          },
          error: (xhr) => {
            console.error('拒绝请求失败:', xhr.statusText)
            this.$message.error(`请求失败: ${xhr.responseJSON?.message || xhr.statusText}`)
          }
        })
      }).catch(() => {
        this.$message.info('已取消操作')
      })
    },

    showDetail (row) {
      this.currentDetail = { ...row }
      this.detailDialogVisible = true
    }
  }
}
</script>

<style scoped>
.role-management-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-area {
  display: flex;
  align-items: center;
}

.pagination-area {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.pagination-area .el-pagination {
  margin-left: 15px;
}
</style>
